package com.madding.shared.encrypt.cert;

import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Map;

import org.bouncycastle.jce.X509Principal;

import com.madding.shared.encrypt.cert.bc.loader.CaCertLoader;
import com.madding.shared.encrypt.cert.bc.util.KeyPairUtil;
import com.madding.shared.encrypt.cert.bc.util.KeyStoreUtil;
import com.madding.shared.encrypt.cert.bc.util.X509PrincipalUtil;
import com.madding.shared.encrypt.cert.dataobject.TDPureCertDo;
import com.madding.shared.encrypt.cert.gen.BCCertGenerator;

/**
 * 类BCCertSystem.java的实现描述：TODO 类实现描述
 * 
 * @author madding.lip Dec 6, 2013 9:23:41 PM
 */
public class BCCertSystem {

    // 颁发证书
    public static TDPureCertDo issueClientCert(String subjectAltName, String cn, String email, String title,
                                               Map<String, String> exts, char[] subjectPasswd) throws Exception {

        X509Principal subject = X509PrincipalUtil.createClientUserPrincipal(cn, email, title);

        KeyPair cCaKeyPair = CaCertLoader.getClientCaKeyPair();
        KeyPair keyPair = KeyPairUtil.generateRSAKeyPair();

        Certificate cUserCert = BCCertGenerator.getIns().createClientUserCert(subjectAltName, subject, exts,
                                                                              keyPair.getPublic(), cCaKeyPair);
        Certificate[] clientUserChain = new Certificate[3];
        clientUserChain[2] = CaCertLoader.getCaCrt();
        clientUserChain[1] = CaCertLoader.getClientCaCrt();
        clientUserChain[0] = cUserCert;
        KeyStore sotre = KeyStoreUtil.getPKCS12KeyStore(subjectAltName, clientUserChain, keyPair);

        return createTDPureCertDo(subjectAltName, sotre, subjectPasswd);
    }

    public static TDPureCertDo createTDPureCertDo(String alias, KeyStore keyStore, char[] passwd) throws Exception {

        TDPureCertDo tdPureCertDo = new TDPureCertDo();
        // set crt file
        Certificate cert = keyStore.getCertificate(alias);
        tdPureCertDo.setCertFile(KeyStoreUtil.getCrtFile(cert));
        X509Certificate X509Cert = (X509Certificate) cert;
        tdPureCertDo.setSerialNumber(X509Cert.getSerialNumber().toString());
        tdPureCertDo.setIssuerDN(X509Cert.getIssuerDN().toString());
        tdPureCertDo.setSubjectDN(X509Cert.getSubjectDN().toString());

        // set key file
        Key key = keyStore.getKey(alias, passwd);
        tdPureCertDo.setKeyFile(KeyStoreUtil.getKeyFile((PrivateKey) key));

        // set p12 file
        String p12file = KeyStoreUtil.getP12File(keyStore, passwd);
        tdPureCertDo.setP12File(p12file);
        // set p12 pwd
        tdPureCertDo.setP12Pwd(String.valueOf(passwd));

        return tdPureCertDo;
    }
}
